package com.wnhz.work.yz.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.base.BaseRVAdapter;
import com.wnhz.work.yz.base.BaseViewHolder;
import com.wnhz.work.yz.bean.AddPersonOneBean;
import com.wnhz.work.yz.bean.AddPersonTeamBean;
import com.wnhz.work.yz.bean.FinishGroup2Bean;
import com.wnhz.work.yz.bean.FinishGroupBean;
import com.wnhz.work.yz.bean.SearcherPerosonBean;
import com.wnhz.work.yz.fragment.group.AddPersonToGroupFragment;
import com.wnhz.work.yz.fragment.group.AddPersonToPersonFragment;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GoToAddPersonActivity extends BaseActivity implements View.OnClickListener {
    private int type = 0;
    private List<Fragment> fragmentList = new ArrayList<>();
    private AddPersonToGroupFragment addGroup;
    private AddPersonToPersonFragment addPerson;
    private FragmentManager fragmentManager;
    private FragmentTransaction transaction;
    private TextView title1, title2;
    private View line1, line2;
    private int textColorNor, textColorCli;
    private EditText search_edit;
    private RecyclerView recycler;
    private LinearLayout all_fragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_go_to_add_person);

        initData();
        initTitle();
        initView();
    }

    private String searchStr = "";

    private void initView() {
        search_edit = (EditText) findViewById(R.id.search_edit);

        recycler = (RecyclerView) findViewById(R.id.searcher);
        recycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        all_fragment = (LinearLayout) findViewById(R.id.all_fragment);
        search_edit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    searchStr = search_edit.getText().toString();
                    if (searchStr.trim().equals("")) {
                        all_fragment.setVisibility(View.VISIBLE);
                        recycler.setVisibility(View.GONE);
                    } else {
                        all_fragment.setVisibility(View.GONE);
                        recycler.setVisibility(View.VISIBLE);
                    }
                    upSearch(searchStr);
                    return true;
                }
                return false;
            }
        });
        //
        textColorNor = getResources().getColor(R.color.text_two);
        textColorCli = getResources().getColor(R.color.main_color);
        findViewById(R.id.shop_title1).setOnClickListener(this);
        findViewById(R.id.shop_title2).setOnClickListener(this);
        title1 = (TextView) findViewById(R.id.shop_title1);
        title2 = (TextView) findViewById(R.id.shop_title2);
        line1 = findViewById(R.id.line1);
        line2 = findViewById(R.id.line2);
        fragmentList.clear();
        addGroup = new AddPersonToGroupFragment();
        addPerson = new AddPersonToPersonFragment();
        fragmentList.add(addGroup);
        fragmentList.add(addPerson);
        fragmentManager = getSupportFragmentManager();
        transaction = fragmentManager.beginTransaction();
        transaction.add(R.id.person_fragment, addGroup);
        transaction.add(R.id.person_fragment, addPerson);
        transaction.hide(addPerson);
        transaction.commit();
    }

    private List<SearcherPerosonBean.InfoEntity> infos = new ArrayList<>();

    private void upSearch(String searchStr) {
        if (searchStr.trim().equals("")) {
            MyToast("请输入人员名称");
            return;
        }

        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("isTeam", 2);
        map.put("keyword", searchStr);
        showDialog();

        XUtil.Post(Url.GETTEAMLISTBYKEYWORD, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("----", "onSuccess:= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    if ("1".equals(res)) {
                        Gson gson = new Gson();
                        SearcherPerosonBean bean = gson.fromJson(result, SearcherPerosonBean.class);
                        infos = bean.getInfo();
                    } else {
                        if ("-1".equals(res)) {
                            info = "请重新登录";
                        }
                        MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                setSearchData();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                closeDialog();
            }
        });


    }

    private void setSearchData() {
        recycler.setAdapter(new BaseRVAdapter(this, infos) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_person;
            }

            @Override
            public void onBind(BaseViewHolder holder, final int position) {
                x.image().bind(holder.getImageView(R.id.head_img), infos.get(position).getUser_img());
                holder.setTextView(R.id.name, infos.get(position).getUser_name());
                holder.setTextView(R.id.phone, infos.get(position).getTelephone());
                ImageView ischoose = holder.getImageView(R.id.ischoose);
                if (infos.get(position).isSelect()) {
                    ischoose.setImageResource(R.mipmap.ic_choose_li);
                } else {
                    ischoose.setImageResource(R.mipmap.ic_choose_nor);
                }
                ischoose.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        infos.get(position).setSelect(!infos.get(position).isSelect());
                        notifyDataSetChanged();
                    }
                });
            }
        });
    }

    private void hideFragment(int index) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        for (int i = 0; i < fragmentList.size(); i++) {
            if (i == index) {
                transaction.show(fragmentList.get(i));
            } else {
                transaction.hide(fragmentList.get(i));
            }

        }
        transaction.commit();
    }

    private void initData() {
        type = getIntent().getIntExtra("type", 0);
    }


    private void initTitle() {
        TextView title = (TextView) findViewById(R.id.view_main_middle_title);
        //title.setTextSize(16);
        if (type == 1) {
            title.setText("选择负责人");
        } else {
            title.setText("选择参与人");
        }
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        TextView submit = (TextView) findViewById(R.id.submit);
        submit.setOnClickListener(this);
        submit.setText("确定");
        submit.setVisibility(View.VISIBLE);
    }

    private int index = 0;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_main_left:
                finish();
                break;
            case R.id.shop_title1:
                hideFragment(0);
                title1.setTextColor(textColorCli);
                title2.setTextColor(textColorNor);
                line1.setVisibility(View.VISIBLE);
                line2.setVisibility(View.INVISIBLE);
                index = 0;
                break;
            case R.id.shop_title2:
                index = 1;
                hideFragment(1);
                title1.setTextColor(textColorNor);
                title2.setTextColor(textColorCli);
                line1.setVisibility(View.INVISIBLE);
                line2.setVisibility(View.VISIBLE);
                break;
            case R.id.submit:
                if (recycler.getVisibility() == View.VISIBLE) {
                    if (index == 0) {
                        Intent intent = new Intent();
                        ArrayList<AddPersonTeamBean.InfoEntity.TeamUserEntity> user = new ArrayList<>();
                        user.clear();
                        for (int i = 0; i < this.infos.size(); i++) {
                            boolean flag = false;

                            if (infos.get(i).isSelect()) {
                                for (int k = 0; k < user.size(); k++) {
                                    if (user.get(k).getUser_id().equals(infos.get(i).getUser_id())) {
                                        flag = true;
                                    }
                                }
                                if (!flag) {
                                    AddPersonTeamBean.InfoEntity.TeamUserEntity in = new AddPersonTeamBean.InfoEntity.TeamUserEntity();
                                    in.setSelect(infos.get(i).isSelect());
                                    in.setUser_id(infos.get(i).getUser_id());
                                    in.setUser_img(infos.get(i).getUser_img());
                                    in.setUser_name(infos.get(i).getUser_name());
                                    in.setTelephone(infos.get(i).getTelephone());
                                    user.add(in);
                                }
                            }
                        }
                        intent.putExtra("type", 0);
                        intent.putExtra("user", user);
                        setResult(Activity.RESULT_OK, intent);
                        finish();
                    } else {
                        Intent intent = new Intent();
                        intent.putExtra("type", 1);
                        ArrayList<AddPersonOneBean.InfoEntity> info = new ArrayList<>();
                        for (int i = 0; i < this.infos.size(); i++) {
                            boolean flag = false;

                            if (infos.get(i).isSelect()) {
                                for (int k = 0; k < info.size(); k++) {
                                    if (info.get(k).getUser_id().equals(infos.get(i).getUser_id())) {
                                        flag = true;
                                    }
                                }
                                if (!flag) {
                                    AddPersonOneBean.InfoEntity in = new AddPersonOneBean.InfoEntity();
                                    in.setSelect(infos.get(i).isSelect());
                                    in.setUser_id(infos.get(i).getUser_id());
                                    in.setUser_img(infos.get(i).getUser_img());
                                    in.setUser_name(infos.get(i).getUser_name());
                                    in.setTelephone(infos.get(i).getTelephone());

                                    info.add(in);
                                }
                            }
                        }
                        intent.putExtra("user", info);
                        setResult(Activity.RESULT_OK, intent);
                        finish();
                    }
                } else {
                    if (index == 0) {
                        FinishGroupBean bean = new FinishGroupBean();
                        bean.setType(type);
                        EventBus.getDefault().post(bean);
                    } else {
                        FinishGroup2Bean bean = new FinishGroup2Bean();
                        bean.setType(type);
                        EventBus.getDefault().post(bean);
                    }
                }
                break;
        }
    }
}
